package lib.bone.admin.controller.research;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.access.module.dict.entity.NepuBookDict;
import lib.bone.admin.anno.FormLock;
import lib.bone.access.constant.BookGroupConst;
import lib.bone.access.constant.ResearchTypeConst;
import lib.bone.nepudata.domain.dto.book.NepuBookAddDTO;
import lib.bone.nepudata.domain.dto.book.NepuBookQueryDTO;
import lib.bone.nepudata.domain.dto.book.NepuBookUpdateDTO;
import lib.bone.ext.draft.NepuDraft;
import lib.bone.ext.draft.NepuDraftService;
import lib.bone.access.config.cycle.NepuCycleService;
import lib.bone.access.module.dict.DictServiceCtl;
import lib.bone.access.module.oss.NepuResearchFileService;
import lib.bone.nepudata.domain.entity.NepuBook;
import lib.bone.nepudata.service.ResearchServiceCtl;
import lib.bone.nepudata.service.impl.NepuBookServiceImpl;
import lib.bone.admin.anno.WebLog;
import lib.bone.admin.constant.MethodTypeConst;
import lib.bone.admin.domain.dto.FileUpdateDTO;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.core.redis.RedisCache;
import lib.bone.common.utils.JsonUtil;
import lib.bone.flow.domain.dto.FlowParam;
import lib.bone.flow.service.FlowWorkCtl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author: kindear
 */
@Slf4j
@RestController
//@RequestMapping("/book")
@RequestMapping("nepu")
@Api(tags = "著作教材")
public class NepuBookController {

    @Autowired
    NepuDraftService draftService;

    @Autowired
    ResearchServiceCtl researchServiceCtl;

    @Autowired
    DictServiceCtl dictServiceCtl;

    @Autowired
    NepuBookServiceImpl nepuBookService;

    @Autowired
    NepuResearchFileService nepuResearchFileService;

    @Autowired
    FlowWorkCtl flowWorkCtl;

    @Autowired
    RedisCache redisCache;

    @Autowired
    NepuCycleService cycleService;

    /**
     * 表单校验
     * @param dto
     * @return
     */
    public String formValid(NepuBookAddDTO dto){
        // 表单重复性校验
        String errMsg = "";
//        Optional<NepuBook> bookOp = nepuBookService.findByBookNameAndFirstAuthor(
//                dto.getBookName(),
//                dto.getFirstAuthor()
//        );
//        if (bookOp.isPresent()) {
//            errMsg = "存在重复记录";
//            return errMsg;
//        }
        Long operator = StpUtil.getLoginIdAsLong();
        Long firstAuthorId = dto.getFirstAuthorId();
        if (!firstAuthorId.equals(operator)){
            errMsg = "您不是负责人，无法申报该项目";
            return errMsg;
        }
        List<Long> userIds = dto.getUserIdList();
        if (userIds.contains(dto.getFirstAuthorId())){
            errMsg = "参与人员中不需添加负责人";
            return errMsg;
        }
        return errMsg;
    }

    @PostMapping("books/storage")
    @FormLock(lockKey = "BOOK_STORE",needLogin = true)
    @ApiOperation(value = "暂存记录",notes = "")
    public ResponseDTO<Object> setStorage(@RequestBody  NepuBookAddDTO dto){
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<Object> dictOp = dictServiceCtl.getById(dto.getBookDictId(),ResearchTypeConst.BOOK);
        if (!dictOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuBookDict dict = (NepuBookDict) dictOp.get();
        String bookGroup = dict.getBookGroup();
        NepuDraft draft = new NepuDraft();
        draft.setFormId(ResearchTypeConst.BOOK+bookGroup);
        draft.setStatus(1);
        draft.setUserId(userId);
        draft.setFormJsonStr(JsonUtil.obj2String(dto));
        return ResponseDTO.succData(draftService.saveOne(draft));
    }

    @GetMapping("books/storage")
    @ApiOperation(value = "获取最新暂存")
    public ResponseDTO<Object> getStorage(@RequestParam("bookGroup") String bookGroup){
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<NepuDraft> draftOp = draftService.getLastDraft(userId,ResearchTypeConst.BOOK+bookGroup);
        if (!draftOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        NepuDraft draft = draftOp.get();
        return ResponseDTO.succData(JsonUtil.string2Obj(draft.getFormJsonStr(),NepuBookAddDTO.class));
    }

    @GetMapping("books/storage/all")
    @ApiOperation(value = "获取全部暂存")
    public ResponseDTO<Object> getAllStorage(@RequestParam("bookGroup") String bookGroup){
        Long userId = StpUtil.getLoginIdAsLong();
        List<NepuDraft> drafts = draftService.getFormAllDrafts(userId,ResearchTypeConst.BOOK+bookGroup);
        return ResponseDTO.succData(drafts);
    }

    @WebLog(module = "nepu-access")
    @FormLock(lockKey = "BOOK_FORM",needLogin = true)
    @PostMapping(value = "books")
    @ApiOperation(value = "新建记录",notes = "")
    public ResponseDTO<Object> saveOne(@RequestBody @Validated NepuBookAddDTO nepuBookAddDTO){
//        // PRE 重复性校验 -- 根据著作教材名称和第一作者
//        Optional<NepuBook> nepuBookOp = nepuBookService.findByBookNameAndFirstAuthor(nepuBookAddDTO.getBookName(),nepuBookAddDTO.getFirstAuthor());
//        if (nepuBookOp.isPresent()){
//            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"重复的著作教材名称和第一作者");
//        }
//        // 1. 获取当前登录用户ID -- 自动拦截未登录用户
//        String operator = StpUtil.getLoginIdAsString();
//        String firstAuthorId = nepuBookAddDTO.getFirstAuthorId().toString();
//        log.info("登录用户为:{},第一作者为:{}",operator,firstAuthorId);
//        if (!firstAuthorId.equals(operator)){
//            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"您不是第一作者，无法申报该项目");
//        }
//        if (nepuBookAddDTO.getUserIdList().contains(nepuBookAddDTO.getFirstAuthorId())){
//            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"参与人员中不需加入第一作者");
//        }
        // 2. 获取当前时间所在周期ID -- 自动拦截不在时间段内的提交
        // 1. 获取操作人员ID
        String operator = StpUtil.getLoginIdAsString();
        // 2. 表单校验
        String errMsg = formValid(nepuBookAddDTO);
        if (!Validator.isEmpty(errMsg)){
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,errMsg);
        }
        //String cycleId = cycleService.getNowCycleId();
        String cycleId = cycleService.getNowResearchCycleId();
        // 3. 获取词典信息
        Optional<Object> bookDictOp = dictServiceCtl.getById(nepuBookAddDTO.getBookDictId(),ResearchTypeConst.BOOK);
        if (!bookDictOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuBookDict dict = (NepuBookDict) bookDictOp.get();
        // 4. 写入记录 并赋值最大工作量
        NepuBook saveEntity = new NepuBook();
        BeanUtil.copyProperties(nepuBookAddDTO,saveEntity,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        // 修复图书工作量写入计算
        saveEntity.setWorkload( dict.getWorkloadStandard() * nepuBookAddDTO.getWordsNumber());
        saveEntity.setCycleId(cycleId);
        NepuBook book = (NepuBook) researchServiceCtl.saveOne(saveEntity);
        // 5. 写入绑定文件信息 -- 修改为异步任务
        List<String> fileIds = nepuBookAddDTO.getFileIds();
        nepuResearchFileService.batchBindFile(ResearchTypeConst.BOOK,book.getId(),fileIds);
        // 6. 构建流程参数
        FlowParam flowParam = new FlowParam(ResearchTypeConst.BOOK,book.getId(),book.getBookName(),operator,null);

        String bookGroup = dict.getBookGroup();
        if (bookGroup.equals(BookGroupConst.BOOK)){
            flowWorkCtl.startProcess("book-check-01",operator,flowParam);
        }else if (bookGroup.equals(BookGroupConst.TEACH_BOOK)){
            flowWorkCtl.startProcess("book-check-02",operator,flowParam);
        }

        return ResponseDTO.succData(book);
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PutMapping(value = "books")
    @ApiOperation(value = "更新单条记录",notes = "")
    public ResponseDTO<Object> updateOne(@RequestBody @Validated NepuBookUpdateDTO nepuBookUpdateDTO){
        Optional<Object> bookOp = researchServiceCtl.getById(nepuBookUpdateDTO.getId(),ResearchTypeConst.BOOK);
        if (!bookOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuBook book = (NepuBook) bookOp.get();
        BeanUtil.copyProperties(nepuBookUpdateDTO,book,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        return ResponseDTO.succData(researchServiceCtl.updateOne(book,ResearchTypeConst.BOOK));
    }

    @GetMapping(value = "books/{id}")
    @ApiOperation(value = "查询单条记录",notes = "")
    public ResponseDTO<Object> getOne(@PathVariable("id") String id){
        Optional<Object> entityOp = researchServiceCtl.getById(id,ResearchTypeConst.BOOK);
        return entityOp.map(ResponseDTO::succData).orElseGet(() -> ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND));
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.DELETE)
    @DeleteMapping(value = "books/{id}")
    @ApiOperation(value = "删除单条记录",notes = "")
    public ResponseDTO<Object> deleteOne(@PathVariable("id") String id){
        return researchServiceCtl.deleteById(id,ResearchTypeConst.BOOK);
    }


    @GetMapping(value = {"books"})
    @ApiOperation(value = "查询全部",notes = "")
    public ResponseDTO<Object> getAll(NepuBookQueryDTO nepuBookQueryDTO){
        Sort sort;
        if(nepuBookQueryDTO.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, nepuBookQueryDTO.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, nepuBookQueryDTO.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(nepuBookQueryDTO.getPageNum() - 1 , nepuBookQueryDTO.getPageSize(), sort);

        NepuBook nepuBook = new NepuBook();
        BeanUtil.copyProperties(nepuBookQueryDTO,nepuBook, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<NepuBook> example = Example.of(nepuBook);
        return ResponseDTO.succData(researchServiceCtl.getAll(pageable,example,ResearchTypeConst.BOOK));

    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PutMapping("books/files")
    @ApiOperation(value = "更新附件信息",notes = "")
    public ResponseDTO<Object> updateFiles(@RequestBody @Validated FileUpdateDTO dto){
        Long userId = StpUtil.getLoginIdAsLong();
        Optional<Object> bookOp = researchServiceCtl.getById(dto.getMapperId(),ResearchTypeConst.BOOK);
        if (!bookOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuBook book = (NepuBook) bookOp.get();
        if (!userId.equals(book.getFirstAuthorId())){
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"非负责人无法修改");
        }
        // 清理之前的附件信息
        nepuResearchFileService.deleteEntityLink(book.getId());
        // 写入新的附件信息
        List<String> fileIds = dto.getFileIds();
        nepuResearchFileService.batchBindFile(ResearchTypeConst.BOOK,book.getId(),fileIds);
        // 返回操作信息
        return ResponseDTO.succMsg("更新成功");
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PutMapping("books/{id}/workload")
    @ApiOperation(value = "修改记录工作量")
    public ResponseDTO<Object> updateWorkload(@PathVariable("id") String id,@RequestParam("workload") Double workload){
        Optional<Object> entityOp = researchServiceCtl.getById(id,ResearchTypeConst.BOOK);
        if (!entityOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到对应课题记录");
        }
        NepuBook book = (NepuBook) entityOp.get();
        String dictId = book.getBookDictId();
        Optional<Object> dictOp = dictServiceCtl.getById(dictId,ResearchTypeConst.BOOK);
        if (!dictOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到课题关联词典记录");
        }
        book.setWorkload(workload);
        // 写入记录
        return ResponseDTO.succData(researchServiceCtl.updateOne(book,ResearchTypeConst.BOOK));
    }

//
//    @DeleteMapping(value = {"/book/{id}"})
//    @ApiOperation(value = "删除单个数据",notes = "传入id，删除信息")
//    public ResponseDTO deleteOneById(@PathVariable("id") String id){
//        return nepuBookService.deleteById(id);
//    }
//
//    @PostMapping(value = {"/book"})
//    @ApiOperation(value = "新建一条数据",notes = "")
//    public ResponseDTO savePaperDict(@RequestBody NepuBook nepuBook){
//        return nepuBookService.save(nepuBook);
//    }
//
//    @PutMapping(value = {"/book"})
//    @ApiOperation(value = "更新一条数据",notes = "")
//    public ResponseDTO updatePaperDict(@RequestBody NepuBook nepuBook){
//        return nepuBookService.save(nepuBook);
//    }

}
